package com.huaishushu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaishushu.common.BaseContext;
import com.huaishushu.common.R;
import com.huaishushu.entity.AddressBook;
import com.huaishushu.service.IAddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * <p>
 * 地址管理 前端控制器
 * </p>
 *
 * @author ChiBaoBaoHuaiShuShu
 * @since 2023-05-28
 */
@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {

    @Autowired
    private IAddressBookService addressBookService;

    /**
     * 添加收货地址
     * @param addressBook
     * @return
     */
    @PostMapping
    public R<String> addressBook(@RequestBody AddressBook addressBook) {
        addressBookService.addressBook(addressBook);
        return R.success("新增地址成功");
    }

    /**
     * 查询当前用户的所有地址
     * @param addressBook
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook) {
        log.info("查询当前用户的所有地址，其id为：{}",BaseContext.getCurrentId());
        List<AddressBook> addressBooks = addressBookService.list(addressBook);

        return R.success(addressBooks);
    }

    /**
     * 根据id来查询地址
     * 在修改地址页面中起到数据回显的作用
     * @param id
     * @return
     */
    @GetMapping("{id}")
    private R<AddressBook> get(@PathVariable("id") Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook != null) {
            return R.success(addressBook);
        }else {
            return R.error("没有这个地址id");
        }
    }

    /**
     * 修改地址
     * @param addressBook
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook) {
        log.info("修改地址，{}",addressBook);
        boolean flag = addressBookService.updateById(addressBook);
        if (flag) {
            return R.success("修改地址成");
        } else {
            return R.error("修改地址失败！！！");
        }
    }

    /**
     * 修改默认地址
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    public R<String> setDefault(@RequestBody AddressBook addressBook) {
        addressBookService.setDefault(addressBook);
        return R.success("设置默认地址成功");
    }

    /**
     * 查询默认地址
     */
    @GetMapping("default")
    public R<AddressBook> getDefault() {
        //获取登录用户的id
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId, userId);
        lqw.eq(AddressBook::getIsDefault, 1);

        AddressBook addressBook = addressBookService.getOne(lqw);

        if (addressBook == null) {
            return R.error("没有找到该对象");
        } else {
            return R.success(addressBook);
        }
    }

}
